package com.example.common.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;

import com.example.common.utils.L;

import java.lang.ref.WeakReference;

public abstract class AbsFragment<T extends ViewDataBinding> extends Fragment {
    protected Activity mActivity;
    protected Context mContext;
    protected T mBinding;
    protected static final int REQUEST_REFRESH_KEY = 44444;
    protected WeakReference<View> mRootView;
    private boolean inited = false;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = getActivity();
        mContext = getContext();
        init(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mFragmentView = null;
        if (mRootView == null || mRootView.get() == null) {
            inited = false;
            mBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
            mFragmentView = mBinding.getRoot();
            //弱引用对象
            mRootView = new WeakReference<>(mFragmentView);
        } else {
            ViewGroup parent = (ViewGroup) mRootView.get().getParent();
            if (parent != null) {
                parent.removeView(mRootView.get());
            }
            mFragmentView = mRootView.get();
        }
        initView(mRootView.get());
        initListener();

        return mRootView.get();
    }

    protected abstract void init(Bundle savedInstanceState);

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        L.e("current fragment ：" + getClass().getSimpleName());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_REFRESH_KEY && resultCode == Activity.RESULT_OK) {
            onRefresh();
        }
    }

    protected abstract void initView(View view);

    protected abstract void initListener();

    protected abstract int getLayoutId();

    protected abstract void onRefresh();
}
